package com.fhminyi.GUI;

import com.fhminyi.dao.UserDao;
import com.fhminyi.model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class UserManagementPanel extends JPanel {
    private JTable userTable;
    private DefaultTableModel userTableModel;
    private JButton deleteUserButton;
    private JButton addUserButton; // 添加用户按钮
    private JButton editUserButton; // 编辑用户按钮

    public UserManagementPanel() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createTitledBorder("用户管理"));

        userTableModel = new DefaultTableModel();
        userTableModel.addColumn("用户ID");
        userTableModel.addColumn("用户名");
        userTableModel.addColumn("邮箱");
        userTableModel.addColumn("电话");
        userTableModel.addColumn("地址");
        userTableModel.addColumn("角色");
        userTableModel.addColumn("密码"); // 添加密码列

        userTable = new JTable(userTableModel);
        JScrollPane userScrollPane = new JScrollPane(userTable);
        add(userScrollPane, BorderLayout.CENTER);

        deleteUserButton = new JButton("删除选中的用户");
        deleteUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selectedRows = userTable.getSelectedRows();
                if (selectedRows.length > 0) {
                    int selectedOption = JOptionPane.showConfirmDialog(UserManagementPanel.this, "确定要删除选中的用户吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                    if (selectedOption == JOptionPane.YES_OPTION) {
                        try {
                            UserDao userDao = new UserDao();
                            for (int row : selectedRows) {
                                int userId = (int) userTableModel.getValueAt(row, 0);
                                userDao.deleteUser(userId);
                            }
                            loadUsers();
                        } catch (SQLException ex) {
                            JOptionPane.showMessageDialog(UserManagementPanel.this, "删除用户失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            }
        });

        addUserButton = new JButton("添加用户"); // 添加用户按钮
        addUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addUser();
            }
        });

        editUserButton = new JButton("编辑用户"); // 编辑用户按钮
        editUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editUser();
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(deleteUserButton);
        buttonPanel.add(addUserButton);
        buttonPanel.add(editUserButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public void loadUsers() {
        userTableModel.setRowCount(0);
        try {
            UserDao userDao = new UserDao();
            List<User> users = userDao.getAllUsers();
            for (User user : users) {
                userTableModel.addRow(new Object[]{user.getUserId(), user.getUsername(), user.getEmail(), user.getPhone(), user.getAddress(), user.getRole(), user.getPassword()}); // 添加密码字段
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载用户失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addUser() {
        // 创建一个对话框来添加用户信息
        JFrame addUserFrame = new JFrame("添加用户");
        addUserFrame.setSize(400, 300);
        addUserFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        addUserFrame.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(7, 2)); // 修改布局以适应新增密码字段

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField(20);
        JLabel emailLabel = new JLabel("邮箱:");
        JTextField emailField = new JTextField(20);
        JLabel phoneLabel = new JLabel("电话:");
        JTextField phoneField = new JTextField(20);
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField(20);
        JLabel roleLabel = new JLabel("角色:");
        JTextField roleField = new JTextField(20);
        JLabel passwordLabel = new JLabel("密码:"); // 添加密码标签
        JPasswordField passwordField = new JPasswordField(20); // 添加密码字段

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(emailLabel);
        panel.add(emailField);
        panel.add(phoneLabel);
        panel.add(phoneField);
        panel.add(addressLabel);
        panel.add(addressField);
        panel.add(roleLabel);
        panel.add(roleField);
        panel.add(passwordLabel);
        panel.add(passwordField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                User newUser = new User();
                newUser.setUsername(usernameField.getText());
                newUser.setEmail(emailField.getText());
                newUser.setPhone(phoneField.getText());
                newUser.setAddress(addressField.getText());
                newUser.setRole(roleField.getText());
                newUser.setPassword(new String(passwordField.getPassword())); // 设置密码

                UserDao userDao = new UserDao();
                try {
                    userDao.addUser(newUser);
                    addUserFrame.dispose();
                    loadUsers();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(addUserFrame, "添加用户失败", "错误", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });

        panel.add(saveButton);
        addUserFrame.add(panel);
        addUserFrame.setVisible(true);
    }

    private void editUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个用户进行编辑", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int userId = (int) userTableModel.getValueAt(selectedRow, 0);
        String username = (String) userTableModel.getValueAt(selectedRow, 1);
        String email = (String) userTableModel.getValueAt(selectedRow, 2);
        String phone = (String) userTableModel.getValueAt(selectedRow, 3);
        String address = (String) userTableModel.getValueAt(selectedRow, 4);
        String role = (String) userTableModel.getValueAt(selectedRow, 5);
        String password = (String) userTableModel.getValueAt(selectedRow, 6); // 获取密码

        JFrame editUserFrame = new JFrame("编辑用户");
        editUserFrame.setSize(400, 350); // 调整窗口大小以适应新增密码字段
        editUserFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        editUserFrame.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(8, 2)); // 修改布局以适应新增密码字段

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField(username, 20);
        JLabel emailLabel = new JLabel("邮箱:");
        JTextField emailField = new JTextField(email, 20);
        JLabel phoneLabel = new JLabel("电话:");
        JTextField phoneField = new JTextField(phone, 20);
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField(address, 20);
        JLabel roleLabel = new JLabel("角色:");
        JTextField roleField = new JTextField(role, 20);
        JLabel passwordLabel = new JLabel("密码:"); // 添加密码标签
        JPasswordField passwordField = new JPasswordField(password, 20); // 添加密码字段

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(emailLabel);
        panel.add(emailField);
        panel.add(phoneLabel);
        panel.add(phoneField);
        panel.add(addressLabel);
        panel.add(addressField);
        panel.add(roleLabel);
        panel.add(roleField);
        panel.add(passwordLabel);
        panel.add(passwordField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                User updatedUser = new User();
                updatedUser.setUserId(userId);
                updatedUser.setUsername(usernameField.getText());
                updatedUser.setEmail(emailField.getText());
                updatedUser.setPhone(phoneField.getText());
                updatedUser.setAddress(addressField.getText());
                updatedUser.setRole(roleField.getText());
                updatedUser.setPassword(new String(passwordField.getPassword())); // 设置密码

                UserDao userDao = new UserDao();
                try {
                    userDao.updateUser(updatedUser);
                    editUserFrame.dispose();
                    loadUsers();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(editUserFrame, "编辑用户失败", "错误", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });

        panel.add(saveButton);
        editUserFrame.add(panel);
        editUserFrame.setVisible(true);
    }
}
